<template>
  <div class="gep-output-calculator">
    <!-- 供给服务数据输入 -->
    <div class="supply-service">
      <h2 class="title">供给服务价值核算</h2>
      <div class="gepD4-input-container">
        <div class="gepD4-input-row">
          <label class="label">农业产品:</label>
          <input type="text" v-model="gepSupplyServiceStore.inAgricultural" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万元）</span>
        </div>
        <div class="gepD4-input-row">
          <label class="label">牧业产品:</label>
          <input type="text" v-model="gepSupplyServiceStore.inAnimalHusbandry" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万元）</span>
        </div>
        <div class="gepD4-input-row">
          <label class="label">林业产值:</label>
          <input type="text" v-model="gepSupplyServiceStore.inForestry" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万元）</span>
        </div>

        <div class="gepD4-input-row">
          <label class="label">渔业产值:</label>
          <input type="text" v-model="gepSupplyServiceStore.inFishery" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万元）</span>
        </div>

        <div class="gepD4-input-row">
          <label class="label">生态能源发电量:</label>
          <input type="text" v-model="gepSupplyServiceStore.inEcologicalEnergy" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万千瓦时）</span>
        </div>

        <div class="gepD4-input-row">
          <label class="label">当地电价:</label>
          <input type="text" v-model="gepSupplyServiceStore.inElectricityPrice" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（元/千瓦时）</span>
        </div>

        <div class="gepD4-input-row">
          <label class="label">水资源:</label>
          <input type="text" v-model="gepSupplyServiceStore.inWaterResources" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万立方米）</span>
        </div>

        <div class="gepD4-input-row">
          <label class="label">当地水价:</label>
          <input type="text" v-model="gepSupplyServiceStore.inLocalWaterPrice" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（元/立方米）</span>
        </div>

      </div>


    </div>

    <!-- 调节服务数据输入 -->
    <div class="regulation-service">
      <h2 class="title">调节服务价值核算</h2>
      <div class="gepD4-input-container">
        <div class="gepD4-input-row">
          <label class="label">保护区面积:</label>
          <input type="text" v-model="gepRegulationServiceStore.inProtectedArea" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（km²）</span>
        </div>
        <div class="gepD4-input-row">
          <label class="label">保育成本:</label>
          <input type="text" v-model="gepRegulationServiceStore.inProtectedCost" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万元/km²）</span>
        </div>

        <div class="gepD4-input-row">
          <label class="label">噪声消减量:</label>
          <input type="text" v-model="gepRegulationServiceStore.inNoiseReductionAmount" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万分贝）</span>
        </div>
        <div class="gepD4-input-row">
          <label class="label">噪声降低成本:</label>
          <input type="text" v-model="gepRegulationServiceStore.inNoiseCost" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（元/分贝）</span>
        </div>
      </div>
    </div>

    <!-- 文化服务数据输入 -->
    <div class="cultural-service">
      <h2 class="title">文化服务价值核算</h2>
      <div class="gepD4-input-container">
        <div class="gepD4-input-row">
          <label class="label">旅游收入:</label>
          <input type="text" v-model="gepCulturalServiceStore.inTourismRevenue" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万元）</span>
        </div>
        <div class="gepD4-input-row">
          <label class="label">城镇人均住房面积:</label>
          <input type="text" v-model="gepCulturalServiceStore.inHousingAreaPerCapita" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（人/m²）</span>
        </div>

        <div class="gepD4-input-row">
          <label class="label ">当地房价:</label>
          <input type="text" v-model="gepCulturalServiceStore.inDisposableIncome" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（元/m²）</span>
        </div>


        <div class="gepD4-input-row">
          <label class="label">总酒店客房数:</label>
          <input type="text" v-model="gepCulturalServiceStore.inHotelRooms" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（间）</span>
        </div>
        <div class="gepD4-input-row">
          <label class="label">客房价格:</label>
          <input type="text" v-model="gepCulturalServiceStore.inRoomPrice" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（元/间）</span>
        </div>

        <div class="gepD4-input-row">
          <label class="label">年均入住率:</label>
          <input type="text" v-model="gepCulturalServiceStore.inOccupancyRate" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（%）</span>
        </div>
        <div class="gepD4-input-row">
          <label class="label">城镇常住人口:</label>
          <input type="text" v-model="gepCulturalServiceStore.inUrbanPopulation" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万人）</span>
        </div>
        <div class="gepD4-input-row">
          <label class="label">日休闲游憩时间:</label>
          <input type="text" v-model="gepCulturalServiceStore.inLeisureTime" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（时/天/人）</span>
        </div>
        <div class="gepD4-input-row">
          <label class="label">人均工资:</label>
          <input type="text" v-model="gepCulturalServiceStore.inAverageIncome" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（元/人时）</span>
        </div>

      </div>
    </div>
    <!--    <border-title title="文化服务价值核算">-->
    <!--      <br>-->
    <!--      <div class="gepD4-input-container">-->
    <!--        <div class="gepD4-input-row">-->
    <!--          <label class="label">旅游收入:</label>-->
    <!--          <input type="number" v-model="gepCulturalServiceStore.inTourismRevenue" class="value-input"/>-->
    <!--          <span>（万元）</span>-->
    <!--        </div>-->
    <!--      </div>-->
    <!--    </border-title>-->

    <!--  计算按钮和结果展示-->
    <!-- 提交按钮 -->
    <div class="bottom-button-container" style="display: flex;justify-content: space-around;padding-left: 10px">

      <button type="submit" @click="calculateGEP"
              class="bg-green-800 hover:bg-green-700 text-white font-bold py-2 px-4 rounded inline-flex items-center">
        <svg class="w-6 h-6 mr-2 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24"
             height="24" fill="none" viewBox="0 0 24 24">
          <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M8.5 11.5 11 14l4-4m6 2a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/>
        </svg>
        <span>提交</span>
      </button>

      <button type="submit" @click="saveDataGEP"
              class="bg-green-800 hover:bg-orange-500 text-white font-bold py-2 px-4 rounded inline-flex items-center">
        <svg class="fill-current w-4 h-4 mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
          <path d="M13 8V2H7v6H2l8 8 8-8h-5zM0 18h20v2H0v-2z"/>
        </svg>
        <span>保存输入</span>
      </button>

      <button type="button" @click="handleClear"
              class="bg-green-800 hover:bg-red-500  text-white font-bold py-2 px-4 rounded inline-flex items-center">
        <svg class="w-6 h-6 mr-2 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24"
             height="24" fill="none" viewBox="0 0 24 24">
          <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M5 7h14m-9 3v8m4-8v8M10 3h4a1 1 0 0 1 1 1v3H9V4a1 1 0 0 1 1-1ZM6 7h12v13a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V7Z"/>
        </svg>
        <span>清空</span>
      </button>

    </div>
  </div>
</template>


<script setup lang="ts">
import {
  useGepCulturalServiceStore,
  useGepDataStore,
  useGepRegulationServiceStore,
  useGepSupplyServiceStore
} from "@/stores/gep";
// import BorderTitle from "@/views/homepage/dashBoardComponents/other/BorderTitle.vue";
import {ref, watch} from "vue";
import {getGepParameterByPath, updateGepResultByPath} from "api/services/gepService";
import {storeToRefs} from "pinia";
import {count} from "api/gepApi";

const gepDataStore = useGepDataStore();
const gepSupplyServiceStore = useGepSupplyServiceStore();
const gepRegulationServiceStore = useGepRegulationServiceStore();
const gepCulturalServiceStore = useGepCulturalServiceStore();
import {updateGepParameterByPath} from '@/api/services/gepService';
import {ElMessage} from 'element-plus';
import {useLoginStore} from "@/stores/login";
import {updateRegulationServiceByPath} from "api/services/regulationService";
import {handleInput, handleInputKeydown} from "api/services/gepFormService";

const loginStore = useLoginStore();
const {gepYear, gepCity, gepTown, gepDistrict, isSelected, isSubmitted, gepValue} = storeToRefs(gepDataStore);
let message = ref('');

const {
  outGepSupplyService,
} = storeToRefs(gepSupplyServiceStore);
const {
  outGepCulturalService,
  inRoomPrice, inHotelRooms, inUrbanPopulation, inTourismRevenue, inDisposableIncome, inHousingAreaPerCapita,
} = storeToRefs(gepCulturalServiceStore);
const {
  outGepRegulationService,
  inProtectedCost,
  inProtectedArea,
  inAirPurification,
  inCarbonSequestration,
  inClimateRegulation,
  inNegativeOxygenIons,
  inOxygenRelease,
  inSoilConservation,
  inWaterPurification,
  inWaterSourceConservation
} = storeToRefs(gepRegulationServiceStore);

function resetAllFormFieldsToZero() {
  // 供给服务字段清零
  gepSupplyServiceStore.$patch({
    inAgricultural: 0,
    inAnimalHusbandry: 0,
    inForestry: 0,
    inFishery: 0,
    inEcologicalEnergy: 0,
    inElectricityPrice: 0,
    inWaterResources: 0,
    inLocalWaterPrice: 0
  });

  // 调节服务字段清零
  gepRegulationServiceStore.$patch({
    inProtectedArea: 0,
    inProtectedCost: 0,
    inNoiseReductionAmount: 0,
    inNoiseCost: 0
  });

  // 文化服务字段清零
  gepCulturalServiceStore.$patch({
    inTourismRevenue: 0,
    inHousingAreaPerCapita: 0,
    inDisposableIncome: 0,
    inHotelRooms: 0,
    inRoomPrice: 0,
    inOccupancyRate: 0,
    inUrbanPopulation: 0,
    inLeisureTime: 0,
    inAverageIncome: 0
  });
}

watch(isSelected, async (newValues) => {
  if (!newValues) return;

  console.log('isSelected:', isSelected.value);
  console.log('await-gepYear', gepYear.value);
  console.log('await-gepCity', gepCity.value);
  console.log('await-gepTown', gepTown.value);
  console.log('await-gepDistrict', gepDistrict.value);

  try {
    const response = await getGepParameterByPath(Number(gepYear.value), gepCity.value, gepDistrict.value, gepTown.value);
    console.log('response——input', response);

    // 更新供给服务 Store
    gepSupplyServiceStore.$patch({
      inAgricultural: Number(response.data.inAgricultural) || 0,
      inAnimalHusbandry: Number(response.data.inAnimalHusbandry) || 0,
      inForestry: Number(response.data.inForestry) || 0,
      inFishery: Number(response.data.inFishery) || 0,
      inEcologicalEnergy: Number(response.data.inEcologicalEnergy) || 0,
      inElectricityPrice: Number(response.data.inElectricityPrice) || 0,
      inWaterResources: Number(response.data.inWaterResources) || 0,
      inLocalWaterPrice: Number(response.data.inLocalWaterPrice) || 0
    });

    // 更新调节服务 Store
    gepRegulationServiceStore.$patch({
      inProtectedArea: Number(response.data.inProtectedArea) || 0,
      inProtectedCost: Number(response.data.inProtectedCost) || 0,
      inNoiseReductionAmount: Number(response.data.inNoiseReductionAmount) || 0,
      inNoiseCost: Number(response.data.inNoiseCost) || 0
    });

    // 更新文化服务 Store
    gepCulturalServiceStore.$patch({
      inTourismRevenue: Number(response.data.inTourismRevenue) || 0,
      inHousingAreaPerCapita: Number(response.data.inHousingAreaPerCapita) || 0,
      inDisposableIncome: Number(response.data.inHousePrice) || 0,
      inHotelRooms: Number(response.data.inHotelRooms) || 0,
      inRoomPrice: Number(response.data.inRoomPrice) || 0,
      inOccupancyRate: Number(response.data.inOccupancyRate) || 0,
      inUrbanPopulation: Number(response.data.inUrbanPopulation) || 0,
      inLeisureTime: Number(response.data.inLeisureTime) || 0,
      inAverageIncome: Number(response.data.inAverageIncome) || 0
    });

    isSelected.value = false;
    console.log('获取资源成功后isSelected:', isSelected.value);

  } catch (error) {
    console.error('获取 GEP 参数失败:', error);

    // 请求失败，清空所有输入字段为 0
    resetAllFormFieldsToZero();

    // ElMessage.warning('未查询到对应年份和地区的参数配置，已清空输入框');
    isSelected.value = false;
  }
});


// 保存gep表单输入数据
async function saveDataGEP() {
  const year = Number(gepYear.value);
  const city = gepCity.value;
  const district = gepDistrict.value;
  const town = gepTown.value;

  if (gepCity.value === '市') {
    // alert("请选择地区！")
    message.value = "请选择地区！"
    ElMessage.warning(message.value);
    return;
  }
  // 组装数据
  const gepData = {
    inAgricultural: gepSupplyServiceStore.inAgricultural,
    inAnimalHusbandry: gepSupplyServiceStore.inAnimalHusbandry,
    inForestry: gepSupplyServiceStore.inForestry,
    inFishery: gepSupplyServiceStore.inFishery,
    inEcologicalEnergy: gepSupplyServiceStore.inEcologicalEnergy,
    inElectricityPrice: gepSupplyServiceStore.inElectricityPrice,
    inWaterResources: gepSupplyServiceStore.inWaterResources,
    inLocalWaterPrice: gepSupplyServiceStore.inLocalWaterPrice,

    inProtectedArea: gepRegulationServiceStore.inProtectedArea,
    inProtectedCost: gepRegulationServiceStore.inProtectedCost,
    inNoiseReductionAmount: gepRegulationServiceStore.inNoiseReductionAmount,
    inNoiseCost: gepRegulationServiceStore.inNoiseCost,

    inTourismRevenue: gepCulturalServiceStore.inTourismRevenue,
    inHousingAreaPerCapita: gepCulturalServiceStore.inHousingAreaPerCapita,
    // inHousePrice
    inHousePrice: gepCulturalServiceStore.inDisposableIncome,
    inHotelRooms: gepCulturalServiceStore.inHotelRooms,
    inRoomPrice: gepCulturalServiceStore.inRoomPrice,
    inOccupancyRate: gepCulturalServiceStore.inOccupancyRate,
    inUrbanPopulation: gepCulturalServiceStore.inUrbanPopulation,
    inLeisureTime: gepCulturalServiceStore.inLeisureTime,
    inAverageIncome: gepCulturalServiceStore.inAverageIncome,
    updater: loginStore.username,
  };
  console.log('gepData', gepData);

  try {
    const result = await updateGepParameterByPath(year, city, district, town, gepData);
    ElMessage.success('参数更新成功');
    console.log('更新成功:', result);
  } catch (error) {
    ElMessage.error('保存失败，请重试');
    console.error('保存 GEP 参数失败:', error);
  }
}

// 保存gep计算结果数据
async function saveResultGEP() {
  const year = Number(gepYear.value);
  const city = gepCity.value;
  const district = gepDistrict.value;
  const town = gepTown.value;

  // 组装数据
  const gepResultData = {
    gepResult: outGepSupplyService.value + outGepCulturalService.value + outGepRegulationService.value,
    materialSupplyValue: gepSupplyServiceStore.outCalcMaterialSupply,                  // 物质供给价值（供给服务总和）
    cleanEnergyValue: gepSupplyServiceStore.outEcologicalEnergy,     // 清洁能源价值
    waterResourcesValue: gepSupplyServiceStore.outCalcWaterResources, // 水资源价值

    tourismHealthValue: gepCulturalServiceStore.outTourismHealth,             // 旅游康养价值
    leisureRecreationValue: gepCulturalServiceStore.outCalcLeisureRecreation, // 休闲游憩价值
    landscapeAppreciationValue: gepCulturalServiceStore.outCalcLandscapeAppreciation, // 景观增值价值

    updater: loginStore.username,
  };
  console.log('gepResultData', gepResultData);

  try {
    const result = await updateGepResultByPath(year, city, district, town, gepResultData);
    ElMessage.success('计算结果保存成功');
    console.log('更新成功:', result);
  } catch (error) {
    ElMessage.error('保存失败，请重试');
    console.error('保存 GEP 参数失败:', error);
  }
}


async function updateNoiseAndBioData(year: number, city: string, district: string, town: string, update: any) {
  try {
    const result = await updateRegulationServiceByPath(year, city, district, town, update);
    // ElMessage.success('调节结果更新成功');
    console.log('更新成功:', result);
  } catch (error) {
    ElMessage.error('保存失败，请重试');
    console.error('保存 GEP 参数失败:', error);
  }
}

async function calculateGEP() {
  // console.log('gepRegion', gepRegion.value)
  if (gepCity.value === '市') {
    // alert("请选择地区！")
    message.value = "请选择地区！"
    ElMessage.warning(message.value);
    return;
  }
  if (gepSupplyServiceStore.inAgricultural === 0) {
    // alert("请填报数据！")
    message.value = "请填报数据！"
    ElMessage.warning(message.value);
    return;
  }
  // if (gepCulturalServiceStore.inUrbanPopulation === 0){
  //   // alert("数据未填报完全！")
  //   message.value = "数据未填报完全!"
  //   ElMessage.warning(message.value);
  //   return;
  // }
  // console.log('计算gep的值outGepSupplyService', outGepSupplyService.value)
  // console.log('计算gep的值outGepCulturalService', outGepCulturalService.value)
  // console.log('计算gep的值outGepRegulationService', outGepRegulationService.value)
  gepValue.value = outGepSupplyService.value + outGepCulturalService.value + outGepRegulationService.value;
  console.log('calculateGEP:gepValue', gepValue.value);

  isSubmitted.value = true;
  count.value += 1;
  // console.log("gep计算的地区是：",gepResultAreaOne.value)
  // 保存参数
  await saveDataGEP();

  // 更新噪声和生物数据
  const update = {
    outCalcBiodiversityProtection: gepRegulationServiceStore.outCalcBiodiversityProtection,
    outCalcNoiseReduced: gepRegulationServiceStore.outCalcNoiseReduced,
  }
  await updateNoiseAndBioData(gepYear.value, gepCity.value, gepDistrict.value, gepTown.value, update);

  // 保存结果
  await saveResultGEP();
  // saveGepResult(gepYear.value, gepResultArea.value, gepValue.value, 1, 1);
  // resetGepData();
}


// 清空表单处理函数
function handleClear() {
  // 用刷新页面代替
  // window.location.reload();
  gepDataStore.reset(); // 调用重置方法
  // console.log('调用重置方法');

}

</script>

<style scoped>
.title {
  font-size: 20px;
  font-weight: bold;
  height: 40px;
  text-align: left;
  color: #caeffa;
  padding-left: 10px;
  padding-top: 5px;
  background-color: #194c51;
}

.regulation-service, .cultural-service {
  margin-top: 29px; /* 与供给服务部分保持一致的间距 */

}


</style>

